<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Application;
use Illuminate\Support\Facades\Redis;

class ApplicationController extends Controller
{
    public function set ()
    {
        for($i = 0; $i < 10; $i++) {
            Redis::sadd('userProfile', $i);
        }
        return 'ok';
    }

    public function delete ()
    {
        Redis::srem('userProfile', 5, 3);
        return 'delete';
    }

    public function get ()
    {
        $info = Redis::smembers('userProfile');
        return $info;
    }

    public function get_post (Request $request)
    {
        return $request->get('name');
    }
    /*
  * 报名保存
  *
  * @param Request $request post请求
  * @return code message
  */
    public function create (Request $request)
    {
        $this->validate($request,[
            'avatar' => 'mimes:jpeg,png,gif'
        ]);
        $input = $request->except('avatar');
        $file = $request->file('avatar');
        $check = DB::table('applications')->where('name', $request->get('name'))->count();
        if($check) {
            return ['code' => '5001', 'message' => 'you have applied'];
        }
        if($file){
            $name = $request->input('name');
            $file->move( public_path().'/upload/image/', $name.".".$file->getClientOriginalExtension());
            $input['avatar'] = $name.".".$file->getClientOriginalExtension();
        }
        if(DB::table('applications')->where('phone', $input['phone'])->value('id'))
        {
            return response()->json([
                'code' => '5000',
                'message' => '已报名'
            ]);
        } else {
            $result = Application::create($input);
            if($result){
                return response()->json([
                    'code' => '200',
                    'message' => 'apply successfully'
                ]);
            } else {
                return response()->json([
                    'code' => '5001',
                    'message' => 'apply fail'
                ]);
            }
        }
    }
}
